const bcrypt = require('bcryptjs')
const { v4 } = require('uuid')
const myDb = require('../../mysql') // 数据库
const { generateToken } = require('../../utils/utils')

module.exports = router => {
  /**
   * 登录
   */
  router.post('/mysql/login', async (ctx, next) => {
    try {
      const data = ctx.request.body
      const result = await myDb.getUserInstance().findOne({
        where: {
          userName: data.userName
        }
      })
      if (result) { // 判断账户是否存在
        let validPass = bcrypt.compareSync(data.password, result.password) // 验证密码是否正确
        if (validPass) { // 比对密码是否正确
          delete result.password // 避免密码暴露
          result.token = generateToken(result.userId) // 生成token
          delete result.userId // 避免userId暴露
          ctx.body = {
            code: 200,
            data: result,
            message: '登陆成功'
          }
        } else {
          ctx.body = {
            code: 401,
            data: null,
            message: '密码错误，请重试'
          }
        }
      } else {
        ctx.body = {
          code: 401,
          data: null,
          message: '账号不存在'
        }
      }

    } catch (err) { // 查询数据库出错
      ctx.logger.error(`${ctx.request.url}--${err}`)
      ctx.body = {
        code: '301',
        data: null,
        message: '账号不存在'
      }
    }
  })

  /**
   * 注册
   */
  router.post('/mysql/register', async (ctx, next) => {
    try {
      const data = ctx.request.body
      let params = {
        userName: data.userName,
        phone: data.phone,
        userId: v4(),
        password: data.password
      }
      await myDb.getUserInstance().create(params)
      ctx.body = {
        code: 200,
        data: null,
        message: '注册成功'
      }
    } catch (err) { // 数据库出错
      console.log(err)
      ctx.logger.error(`${ctx.request.url}--${JSON.stringify(err)}`)
      ctx.body = {
        code: '301',
        data: null,
        message: '注册失败'
      }
    }
  })

  /**
   * 清空所有表
   */
  router.post('/mysql/clear/all', async (ctx, next) => {
    myDb.drop()
    ctx.body = {
      code: 200,
      data: null,
      message: '清除成功'
    }
  })

  /**
   * 清空所有表
   */
  router.get('/mysql/user/list', async (ctx, next) => {
    try {
      let data = ctx.query
      let _page = parseInt(data.page)
      let _pageSize = parseInt(data.pageSize)
      let conditions = {
        offset: (_page - 1) * _pageSize, // 从第几个开始查询 -- 用于分页
        limit: _pageSize // 每次查询限制数量 -- 用于分页
      }
      let result = await myDb.getUserInstance().findAndCountAll(conditions)
      ctx.body = {
        code: 200,
        data: result,
        message: ''
      }
    } catch (err) { // 数据库出错
      ctx.logger.error(`${ctx.request.url}--${JSON.stringify(err)}`)
      ctx.body = {
        code: '301',
        data: null,
        message: '查询失败'
      }
    }
  })
}
